//
//  LDDErandApplyListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-8-17.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "LDDErandApplyListViewController.h"
#import "CommonPickerViewController.h"
#import "ReportParamInfo.h"
#import "ErandReportViewController.h"

@interface LDDErandApplyListViewController () <CommonPickerDelegate>

@property (weak, nonatomic) IBOutlet UILabel *deptLbl;
@property (weak, nonatomic) IBOutlet UILabel *nameLbl;
@property (weak, nonatomic) IBOutlet UILabel *gonghaoLbl;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) CommonPickerViewController *picker;
@property (nonatomic, assign) NSInteger showingIndex;

@property (nonatomic, strong) NSMutableArray *depts; //职位列表
@property (nonatomic, strong) NSMutableArray *names; //督导姓名列表
@property (nonatomic, strong) NSMutableArray *gonghaos; //督导工号列表

@property (nonatomic, strong) NSMutableArray *applyList;

- (IBAction)selectSearchItemsAction:(id)sender;
- (IBAction)searchAction:(id)sender;

@end

@implementation LDDErandApplyListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.applyList = [NSMutableArray array];
    
    self.depts = [NSMutableArray array];
    self.names = [NSMutableArray array];
    self.gonghaos = [NSMutableArray array];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    
    self.title = @"督导出差列表";
    [super viewWillAppear:animated];
    
    self.showingIndex = -1;
    
    [self searchAction:nil];
}

- (void)refreshViewByReloadData {
    [self searchAction:nil];
}

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

//获取督导出差列表查询参数
- (void)getErandReportParamListWithDept:(NSString *)zw name:(NSString *)name gonghao:(NSString *)gh {
    UserInfo *user = [UserInfo instance];
    NSString *yhm = [user.info objectForKeyOrNil:@"yhm"];
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                           yhm,@"yhm", nil];
    if ([zw length] > 0) {
        [param setObject:zw forKey:@"zw"];
    }
    if ([name length] > 0) {
        [param setObject:name forKey:@"xm"];
    }
    if ([gh length] > 0) {
        [param setObject:gh forKey:@"gh"];
    }
    [self.networkManager requestWithMethod:showUserParamByCondition parameter:param delegate:self];
    [self.HUD show:YES];
}

- (IBAction)selectSearchItemsAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    NSInteger tag = btn.tag;
    
    self.showingIndex = tag;
    
    NSString *dept = self.deptLbl.text;
    NSString *name = self.nameLbl.text;
    NSString *gh = self.gonghaoLbl.text;
    if ([dept length] == 0 || [dept isEqualToString:@"选择职位"]) {
        dept = @"";
    }
    if ([name length] == 0 || [name isEqualToString:@"选择姓名"]) {
        name = @"";
    }
    if ([gh length] == 0 || [gh isEqualToString:@"选择工号"]) {
        gh = @"";
    }
    [self getErandReportParamListWithDept:dept name:name gonghao:gh];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    if (self.picker.parentViewController == nil) {
        self.picker = (CommonPickerViewController *)[storyboard instantiateViewControllerWithIdentifier:@"CommonPicker"];
        _picker.delegate = self;
//        _picker.datas = [NSArray arrayWithObjects:componentData, nil];
        _picker.view.tag = tag;
        
        _picker.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.bounds));
        AppDelegate *app = [AppDelegate sharedDelegate];
        [app.window addSubview:_picker.view];
    } else {
//        _picker.datas = [NSArray arrayWithObjects:componentData, nil];
        _picker.view.tag = tag;
//        [self.picker reloadData];
    }
}

- (IBAction)searchAction:(id)sender {
    if (!self.isRefreshing) {
        self.isRefreshing = YES;
        NSString *dept = self.deptLbl.text;
        NSString *name = self.nameLbl.text;
        NSString *gh = self.gonghaoLbl.text;
        if ([dept length] == 0 || [dept isEqualToString:@"选择职位"]) {
            dept = @"";
        }
        if ([name length] == 0 || [name isEqualToString:@"选择姓名"]) {
            name = @"";
        }
        if ([gh length] == 0 || [gh isEqualToString:@"选择工号"]) {
            gh = @"";
        }
        
        UserInfo *user = [UserInfo instance];
        NSString *yhm = [user.info objectForKeyOrNil:@"yhm"];
        NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                               yhm,@"yhm", nil];
        
        if ([dept length] > 0) {
            [param setObject:dept forKey:@"zw"];
        }
        if ([name length] > 0) {
            [param setObject:name forKey:@"xm"];
        }
        if ([gh length] > 0) {
            [param setObject:gh forKey:@"gh"];
        }
        [self.networkManager requestWithMethod:showUserBusinessListByCondition parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

#pragma mark - CommonPickerDelegate
- (void)picker:(CommonPickerViewController *)picker didSelectedItemIndexSet:(NSDictionary *)selectedItems {
    NSInteger index = [[selectedItems objectForKey:[NSNumber numberWithInt:0]] integerValue];
    
    NSInteger tag = picker.view.tag;
    
    NSArray *componentData = nil;
    if (tag == 100) { //职位
        if (index == 0) {
            self.deptLbl.text = @"选择职位";
        } else {
            componentData = self.depts;
            self.deptLbl.text = [componentData objectAtIndex:index];
        }
    } else if (tag == 101) {
        if (index == 0) {
            self.nameLbl.text = @"选择姓名";
        } else {
            componentData = self.names;
            self.nameLbl.text = [componentData objectAtIndex:index];
        }
    } else if (tag == 102) {
        if (index == 0) {
            self.gonghaoLbl.text = @"选择工号";
        } else {
            componentData = self.gonghaos;
            self.gonghaoLbl.text = [componentData objectAtIndex:index];
        }
    }
    self.showingIndex = -1;
    self.picker = nil;
    [self searchAction:nil];
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if (methodId == showUserBusinessListByCondition) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                [self.applyList removeAllObjects];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSDictionary class]]) {
                        NSArray *results = [dataObject objectForKeyOrNil:@"updateAppListByTime"];
                        if (![results isKindOfClass:[NSNull class]] && [results count] > 0) {
                            [self.applyList  addObjectsFromArray:results];
                        }
                    } else if ([dataObject isKindOfClass:[NSArray class]]) {
                        [self.applyList addObjectsFromArray:dataObject];
                    }
                }
                
                [self.tableView reloadData];
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"督导出差列表查询失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
    } else if (methodId == showUserParamByCondition) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                [self.depts removeAllObjects];
                [self.names removeAllObjects];
                [self.gonghaos removeAllObjects];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSArray class]]) {
                        if ([dataObject count] > 0) {
                            NSDictionary *dict = [dataObject objectAtIndex:0];
                            NSString *deptString = [dict objectForKeyOrNil:@"zw"];
                            NSString *ghString = [dict objectForKeyOrNil:@"gh"];
                            NSString *nameString = [dict objectForKeyOrNil:@"xm"];
                            
                            NSArray *deptArr = [deptString componentsSeparatedByString:@","];
                            NSArray *ghArr = [ghString componentsSeparatedByString:@","];
                            NSArray *nameArr = [nameString componentsSeparatedByString:@","];
                            
                            self.depts = [NSMutableArray arrayWithArray:deptArr];
                            self.names = [NSMutableArray arrayWithArray:nameArr];
                            self.gonghaos = [NSMutableArray arrayWithArray:ghArr];
                            
                        }
                    }
                }
            }
        }
        
        NSMutableArray *componentData = nil;
        if (self.showingIndex == 100) { //职位
            componentData = self.depts;
        } else if (self.showingIndex == 101) {
            componentData = self.names;
        } else if (self.showingIndex == 102) {
            componentData = self.gonghaos;
        }
        [componentData insertObject:@"全部" atIndex:0];
        self.picker.datas = [NSArray arrayWithObjects:componentData, nil];
        [self.picker reloadData];
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"督导出差列表查询失败，请稍后重试";
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.applyList count];
    //    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"LDDErandApplyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    UILabel *erandPcLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dudaoNameLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *dudaoGhLbl = (UILabel *)[cell.contentView viewWithTag:104];
    UILabel *dudaoZwLbl = (UILabel *)[cell.contentView viewWithTag:105];
    UILabel *jxsNameLbl = (UILabel *)[cell.contentView viewWithTag:106];
    UILabel *jxsCodeLbl = (UILabel *)[cell.contentView viewWithTag:107];
    UILabel *erandReasonLbl = (UILabel *)[cell.contentView viewWithTag:108];
    UILabel *erandPlaceLbl = (UILabel *)[cell.contentView viewWithTag:109];
    
    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        NSString *pc = [cellData objectForKeyOrNil:@"pc"];
        NSString *erandDate = [cellData objectForKeyOrNil:@"ccsj"];
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *dept = [cellData objectForKeyOrNil:@"zw"];
        NSString *jxsName = [cellData objectForKeyOrNil:@"jxsmc"];
        NSString *jxsCode = [cellData objectForKeyOrNil:@"jxsdm"];
        NSString *reason = [cellData objectForKeyOrNil:@"ccmd"];
        NSString *place = [cellData objectForKeyOrNil:@"ccdd"];
        
        if ([pc length] == 0) {
            pc = @"";
        }
        if ([erandDate length] == 0) {
            erandDate = @"";
        }
        if ([dudaoName length] == 0) {
            dudaoName = @"";
        }
        if ([dudaoCode length] == 0) {
            dudaoCode = @"";
        }
        if ([dept length] == 0) {
            dept = @"";
        }
        if ([jxsName length] == 0) {
            jxsName = @"";
        }
        if ([jxsCode length] == 0) {
            jxsCode = @"";
        }
        if ([reason length] == 0) {
            reason = @"";
        }
        if ([place length] == 0) {
            place = @"";
        }
        
        erandPcLbl.text = pc;
        dateLbl.text = erandDate;
        dudaoNameLbl.text = dudaoName;
        dudaoGhLbl.text = dudaoCode;
        dudaoZwLbl.text = dept;
        jxsNameLbl.text = jxsName;
        jxsCodeLbl.text = jxsCode;
        erandReasonLbl.text = reason;
        erandPlaceLbl.text = place;
        
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 74.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ErandReportViewController *reportVC = (ErandReportViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ErandReportView"];
    
    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        reportVC.applyInfo = cellData;
    }
    reportVC.fromLeader = YES;
    [self.navigationController pushViewController:reportVC animated:YES];
}

@end
